package trabajoISW2.presentation.server;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import trabajoISW2.data.AuthorDAO;
import trabajoISW2.data.BookDAO;
import trabajoISW2.data.IAuthorDAO;
import trabajoISW2.data.IBookDAO;
import trabajoISW2.data.IPublisherDAO;
import trabajoISW2.data.ISubjectDAO;
import trabajoISW2.data.PublisherDAO;
import trabajoISW2.data.SubjectDAO;
import trabajoISW2.domain.implementations.Book;
import trabajoISW2.presentation.client.BooksManagementUseCase;
import trabajoISW2.presentation.shared.BookDTO;
import trabajoISW2.presentation.shared.BookMapper;

public class BooksManagement implements BooksManagementUseCase{

	private IBookDAO bDao = new BookDAO();
	private IAuthorDAO aDao = new AuthorDAO();
	private IPublisherDAO pDao = new PublisherDAO();
	private ISubjectDAO sDao = new SubjectDAO();
	
	@Override
	public List<BookDTO> searchBookByTitle(String title) {
		List<Book> books = bDao.getBookByTitle(title);
		
		List<BookDTO> dtos = new LinkedList<BookDTO>();
		if (!books.isEmpty()){
			Book b;
			BookDTO dto;
			Iterator<Book> it = books.iterator();
			while (it.hasNext()){
				b = it.next();
				dto = BookMapper.createDTO(b);
				dtos.add(dto);
			}
		}
		return dtos;
	}

	@Override
	public List<BookDTO> searchBookByAuthor(String author) {
		List<Book> books = aDao.getBookByAuthor(author);
		
		List<BookDTO> dtos = new LinkedList<BookDTO>();
		if (!books.isEmpty()){
			Book b;
			BookDTO dto;
			Iterator<Book> it = books.iterator();
			while (it.hasNext()){
				b = it.next();
				dto = BookMapper.createDTO(b);
				dtos.add(dto);
			}
		}
		return dtos;
	}

	@Override
	public BookDTO searchBookByIsbn(String isbn) {
		Book b = bDao.getBook(isbn);
		
		BookDTO dto = null;
		if (b != null)
			dto = BookMapper.createDTO(b);
		return dto;
	}

	@Override
	public List<BookDTO> searchBookBySubject(String subject) {
		List<Book> books = sDao.getBookBySubject(subject);
		
		List<BookDTO> dtos = new LinkedList<BookDTO>();
		if (!books.isEmpty()){
			Book b;
			BookDTO dto;
			Iterator<Book> it = books.iterator();
			while (it.hasNext()){
				b = it.next();
				dto = BookMapper.createDTO(b);
				dtos.add(dto);
			}
		}
		return dtos;
	}

	@Override
	public List<BookDTO> searchBookByPublisher(String publisher) {
		List<Book> books = pDao.getBookByPublisher(publisher);
		
		List<BookDTO> dtos = new LinkedList<BookDTO>();
		if (!books.isEmpty()){
			Book b;
			BookDTO dto;
			Iterator<Book> it = books.iterator();
			while (it.hasNext()){
				b = it.next();
				dto = BookMapper.createDTO(b);
				dtos.add(dto);
			}
		}
		return dtos;
	}

	@Override
	public BookDTO showBookDetails(String isbn) {
		Book b = bDao.getBook(isbn);
				
		BookDTO dto = BookMapper.createDTO(b);
		return dto;
	}

}
